<?php

namespace App\Services;

use App\Strategys\Message\CustomerMessage;
use App\Strategys\Message\TouristMessage;
use App\Strategys\Message\UsersMessage;
use App\Traits\MessageResponseTraits;

class SocketService
{
    use MessageResponseTraits;

    const USER = 1;
    const CUSTOMER = 2;
    const TOURISTS = 3;

    /**
     * 连接用户类型
     * @static
     * @var array $connectUserType
     */
    public static $connectUser = [
        1 => '平台会员',
        2 => '平台客服',
        3 => '未登录的游客'
    ];

    /**
     * 对象列表
     * @static
     * @var array $messageClass
     */
    public static $messageClass = [
        1 => UsersMessage::class,
        2 => CustomerMessage::class,
        3 => TouristMessage::class
    ];

    /**
     * socket 连接成功
     * @param $ws      object
     * @param $request object
     * @return void
     */
    public function onOpen($ws, $request)
    {
        $user_type = isset($request->get['user_type']) && !empty($request->get['user_type']) ? $request->get['user_type'] : 0;
        $user_id   = isset($request->get['user_id']) && !empty($request->get['user_id']) ? intval($request->get['user_id']) : 0;

        // 连接数据错误
        if (
            (!in_array($user_type, array_keys(self::$messageClass))) ||
            (in_array($user_type, [1, 2]) && empty($user_id))
        ) {
            $ws->push($request->fd, $this->failed(['message' => '操作失败，初始化参数错误！']));
        }

        $messageClass = new self::$messageClass[$user_type]($ws, $request->fd);
        $messageClass->online($user_id);

    }

    /**
     * 消息响应事件
     * @param $ws     object
     * @param $frame  object
     * @return void
     */
    public function onMessage($ws, $frame)
    {
        $data = json_decode($frame->data, true);
        $user_type = isset($data['user_type']) && !empty($data['user_type']) ? $data['user_type'] : 0;
        if (empty($user_type) || !in_array($user_type, array_keys(self::$messageClass))) {
            $ws->push($frame->fd, $this->failed(['message' => '错误的链接类型~']));
        }

        $messageClass = new self::$messageClass[$user_type]($ws, $frame->fd);
        $messageClass->sendMessage($data);
    }

    /**
     * 关闭回调
     * @param object $ws
     * @param int    $fd
     * @return void
     */
    public function onClose ($ws, $fd) {

        $service   = new ChatRoomService();
        $user_info = $service->getCacheUserData($fd);

        if (!empty($user_info)) {
            $messageClass = new self::$messageClass[$user_info['user_type']]($ws, $fd);
            $messageClass->close($user_info);
        }
    }

}
